package com.hxzy.controller.admin;

import com.hxzy.common.constant.Constants;
import com.hxzy.common.core.controller.BaseController;
import com.hxzy.common.core.domain.AjaxResult;
import com.hxzy.common.core.domain.entity.User;
import com.hxzy.common.security.SecurityUtils;
import com.hxzy.framework.web.security.service.LoginService;
import com.hxzy.system.dto.LoginUserDTO;
import com.hxzy.system.service.MenuService;
import com.hxzy.system.service.RoleService;
import com.hxzy.system.vo.MenuTreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 类说明
 *
 * @author admin
 * @date 2021-09-24
 */
@RestController
@RequestMapping(value = "/admin")
public class LoginController  extends BaseController {

    @Autowired
    private StringRedisTemplate  stringRedisTemplate;

    @Autowired
    private LoginService loginService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    @PostMapping(value = "/login")
    public AjaxResult login(@RequestBody LoginUserDTO loginUserDTO){

        String token=this.loginService.login(loginUserDTO);

        AjaxResult ajaxResult=AjaxResult.success();
        //令牌发送给前端(令牌就是redis中的key)
        ajaxResult.put(Constants.TOKEN,  token);

        return ajaxResult;
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo()
    {
        User user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = this.roleService.getRolePermission(user.getUserId());
        // 权限集合
        Set<String> permissions = this.menuService.selectMenuPermsByUserId(user.getUserId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息(首页左边菜单)
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<MenuTreeVo> menus = menuService.selectMenuTreeByUserId(userId);
        //构造成前端需要的格式
        return AjaxResult.success(menuService.buildMenus(menus));
    }

}
